package com.xunshangwang.pinhaohuo.ui.activities.address;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;

import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.ui.activities.BaseActivity;
import com.xunshangwang.pinhaohuo.ui.fragments.address.ProvinceFragment;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import tool.library.ToastTool;

/**
 * Created by xzp on 16/2/15.
 */
public class SelectAddressActivity extends BaseActivity{
    private List<Province> mProvinceList;
    private AddressTask mTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_address);
        mTask=new AddressTask();
        mTask.execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mTask!=null && !mTask.isCancelled())
            mTask.cancel(true);
    }
    public List<Province> getProvinceList(){
        return mProvinceList;
    }

    @Override
    public void onBackPressed() {
        if(!onStackBack())
            super.onBackPressed();
    }

    @Override
    protected void onHomeAsUpClick() {
       if(!onStackBack())
           super.onHomeAsUpClick();

    }
    private boolean onStackBack(){
        FragmentManager fragmentManager=getSupportFragmentManager();
        int count=fragmentManager.getBackStackEntryCount();
        if(count>0){
            fragmentManager.popBackStack();
            switch (count){
                case 1:
                    getTitleText().setText(R.string.select_province);
                    break;
                case 2:
                    getTitleText().setText(R.string.select_city);
                    break;
                default:
                    getTitleText().setText("选择地址");
                    break;
            }
            return true;
        }
        return false;
    }
    private class AddressTask extends AsyncTask<Void,Integer,Boolean>{
        @Override
        protected void onPreExecute() {
            mProvinceList=new ArrayList<Province>();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                InputStream is=getResources().getAssets().open("city.json");
                BufferedReader reader=new BufferedReader(new InputStreamReader(is));
                StringBuffer stringBuffer=new StringBuffer();
                String line;
                while ((line=reader.readLine())!=null){
                    stringBuffer.append(line);
                }
                if(isCancelled())
                    return false;
                JSONObject regionsJson=new JSONObject(stringBuffer.toString()).getJSONObject("regions");
                if(isCancelled())
                    return false;
                JSONArray provinceJson=regionsJson.getJSONArray("1");
                HashMap<Integer,Province> provinceMap=new HashMap<Integer,Province>();
                for (int i=0;i<provinceJson.length();i++){
                    Province province=new Province();
                    JSONObject jsonObject=provinceJson.getJSONObject(i);
                    province.setId(jsonObject.getInt("region_id"));
                    province.setName(jsonObject.getString("region_name"));
                    mProvinceList.add(province);
                    provinceMap.put(province.getId(),province);
                }
                if(isCancelled())
                    return false;
                JSONArray cityJson=regionsJson.getJSONArray("2");
                HashMap<Integer,City> cityMap=new HashMap<Integer,City>();
                for(int i=0;i<cityJson.length();i++){
                    City city=new City();
                    JSONObject jsonObject=cityJson.getJSONObject(i);
                    city.setId(jsonObject.getInt("region_id"));
                    city.setName(jsonObject.getString("region_name"));
                    Province parent=provinceMap.get(jsonObject.getInt("parent_id"));
                    parent.getCityList().add(city);
                    cityMap.put(city.getId(),city);
                }
                if(isCancelled())
                    return false;
                JSONArray districtJson=regionsJson.getJSONArray("3");
                for(int i=0;i<districtJson.length();i++){
                    District district=new District();
                    JSONObject jsonObject=districtJson.getJSONObject(i);
                    district.setId(jsonObject.getInt("region_id"));
                    district.setName(jsonObject.getString("region_name"));
                    City parent=cityMap.get(jsonObject.getInt("parent_id"));
                    parent.getDistrictList().add(district);
                }

            } catch (Exception e) {
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            mTask=null;
            if(aBoolean){
                FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.fragment_container, new ProvinceFragment(), "province");
                //transaction.addToBackStack(null);
                getTitleText().setText(R.string.select_province);
                transaction.commitAllowingStateLoss();
            }
            else {
                ToastTool.showToast("读取城市列表失败");
            }
        }
    }
    public static class Province{
        int id;
        String name;
        List<City> cityList;
        public Province(){
            cityList=new ArrayList<City>();
        }
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<City> getCityList() {
            return cityList;
        }

        public void setCityList(List<City> cityList) {
            this.cityList = cityList;
        }
    }
    public static class City{
        int id;
        String name;
        List<District> districtList;
        public City(){
            districtList=new ArrayList<District>();
        }
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<District> getDistrictList() {
            return districtList;
        }

        public void setDistrictList(List<District> districtList) {
            this.districtList = districtList;
        }
    }
    public static class District{
        int id;
        String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}
